<template>
  <el-dialog
    v-model="dialogVisible"
    :title="mode === 'create' ? '新增敏感词' : '编辑敏感词'"
    width="600px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      v-loading="loading"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="敏感词" prop="word">
        <el-input
          v-model="form.word"
          placeholder="请输入敏感词内容"
          maxlength="100"
          show-word-limit
          clearable
        />
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-select
          v-model="form.type"
          placeholder="请选择敏感词类型"
          style="width: 100%"
        >
          <el-option
            v-for="type in sensitiveWordTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="严重程度" prop="severity">
        <el-select
          v-model="form.severity"
          placeholder="请选择严重程度"
          style="width: 100%"
        >
          <el-option
            v-for="severity in severityLevels"
            :key="severity.value"
            :label="severity.label"
            :value="severity.value"
          >
            <div class="severity-option">
              <el-tag
                size="small"
                :style="{
                  backgroundColor:
                    SensitiveWordManagementUtils.getSeverityColor(
                      severity.value
                    ),
                  color: '#ffffff',
                  border: 'none'
                }"
              >
                {{ severity.label }}
              </el-tag>
              <span class="severity-desc">{{ severity.description }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="过滤模式" prop="filterMode">
        <el-radio-group v-model="form.filterMode">
          <el-radio :value="FilterMode.REPLACE">
            <el-tag type="success" size="small">替换模式</el-tag>
            <span class="mode-desc">将敏感词替换为指定文本</span>
          </el-radio>
          <el-radio :value="FilterMode.BLOCK">
            <el-tag type="warning" size="small">拦截模式</el-tag>
            <span class="mode-desc">直接拦截包含敏感词的内容</span>
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        v-if="form.filterMode === FilterMode.REPLACE"
        label="替换文本"
        prop="replacement"
      >
        <el-input
          v-model="form.replacement"
          placeholder="请输入替换文本，默认为 ***"
          maxlength="50"
          show-word-limit
          clearable
        />
        <div class="form-tip">
          <el-text type="info" size="small">
            留空则使用默认替换文本 "***"
          </el-text>
        </div>
      </el-form-item>

      <el-form-item label="描述信息">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入描述信息（可选）"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="标签">
        <el-select
          v-model="form.tags"
          multiple
          filterable
          allow-create
          placeholder="请选择或输入标签"
          style="width: 100%"
        >
          <el-option
            v-for="tag in commonTags"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
        <div class="form-tip">
          <el-text type="info" size="small">
            可以选择常用标签或输入自定义标签
          </el-text>
        </div>
      </el-form-item>

      <el-form-item label="状态">
        <el-switch
          v-model="form.status"
          :active-value="1"
          :inactive-value="0"
          active-text="启用"
          inactive-text="禁用"
        />
        <div class="form-tip">
          <el-text type="info" size="small">
            启用后该敏感词将参与内容过滤
          </el-text>
        </div>
      </el-form-item>

      <!-- 预览区域 -->
      <el-form-item label="效果预览">
        <el-card class="preview-card">
          <div class="preview-content">
            <div class="preview-item">
              <span class="preview-label">敏感词：</span>
              <el-text class="preview-word" type="primary">
                {{ form.word || "示例敏感词" }}
              </el-text>
            </div>
            <div class="preview-item">
              <span class="preview-label">处理方式：</span>
              <el-tag
                :type="
                  form.filterMode === FilterMode.REPLACE ? 'success' : 'warning'
                "
                size="small"
              >
                {{
                  form.filterMode === FilterMode.REPLACE ? "替换为" : "直接拦截"
                }}
                {{
                  form.filterMode === FilterMode.REPLACE
                    ? form.replacement || "***"
                    : ""
                }}
              </el-tag>
            </div>
            <div class="preview-item">
              <span class="preview-label">示例文本：</span>
              <div class="preview-text">
                这是一段包含
                <span
                  v-if="form.filterMode === FilterMode.REPLACE"
                  class="replaced-word"
                >
                  {{ form.replacement || "***" }}
                </span>
                <span v-else class="blocked-text">[内容被拦截]</span>
                的示例文本
              </div>
            </div>
          </div>
        </el-card>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ mode === "create" ? "创建" : "更新" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, nextTick } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import {
  getSensitiveWordDetailApi,
  createSensitiveWordApi,
  updateSensitiveWordApi,
  SensitiveWordType,
  SeverityLevel,
  FilterMode,
  SensitiveWordManagementUtils,
  type CreateSensitiveWordParams,
  type UpdateSensitiveWordParams
} from "@/api/sensitive-word-management";

interface Props {
  /** 对话框可见性 */
  visible: boolean;
  /** 敏感词ID（编辑模式） */
  wordId?: number | null;
  /** 模式 */
  mode: "create" | "edit";
}

const props = withDefaults(defineProps<Props>(), {
  wordId: null
});

const emit = defineEmits<{
  "update:visible": [visible: boolean];
  success: [];
}>();

// 响应式数据
const loading = ref(false);
const submitting = ref(false);
const formRef = ref<FormInstance>();

// 表单数据
const form = reactive<CreateSensitiveWordParams & { id?: number }>({
  word: "",
  type: SensitiveWordType.PROFANITY,
  severity: SeverityLevel.MEDIUM,
  filterMode: FilterMode.REPLACE,
  replacement: "",
  description: "",
  tags: [],
  status: 1
});

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

// 选项数据
const sensitiveWordTypes = [
  { label: "脏话", value: SensitiveWordType.PROFANITY },
  { label: "政治敏感", value: SensitiveWordType.POLITICS },
  { label: "广告", value: SensitiveWordType.ADVERTISEMENT },
  { label: "暴力内容", value: SensitiveWordType.VIOLENCE },
  { label: "违法内容", value: SensitiveWordType.ILLEGAL },
  { label: "垃圾信息", value: SensitiveWordType.SPAM }
];

const severityLevels = [
  {
    label: "轻微",
    value: SeverityLevel.LIGHT,
    description: "轻微不当，建议替换"
  },
  {
    label: "一般",
    value: SeverityLevel.NORMAL,
    description: "一般不当，需要处理"
  },
  {
    label: "中等",
    value: SeverityLevel.MEDIUM,
    description: "中等严重，必须处理"
  },
  {
    label: "严重",
    value: SeverityLevel.SERIOUS,
    description: "严重违规，直接拦截"
  },
  {
    label: "极严重",
    value: SeverityLevel.CRITICAL,
    description: "极其严重，立即拦截"
  }
];

const commonTags = [
  "测试",
  "示例",
  "违规",
  "不当",
  "敏感",
  "政治",
  "广告",
  "暴力",
  "违法",
  "垃圾"
];

// 表单验证规则
const rules: FormRules = {
  word: [
    { required: true, message: "请输入敏感词内容", trigger: "blur" },
    {
      min: 1,
      max: 100,
      message: "敏感词长度应在 1 到 100 个字符之间",
      trigger: "blur"
    }
  ],
  type: [{ required: true, message: "请选择敏感词类型", trigger: "change" }],
  severity: [{ required: true, message: "请选择严重程度", trigger: "change" }],
  filterMode: [
    { required: true, message: "请选择过滤模式", trigger: "change" }
  ],
  replacement: [
    { max: 50, message: "替换文本长度不能超过 50 个字符", trigger: "blur" }
  ],
  description: [
    { max: 500, message: "描述信息长度不能超过 500 个字符", trigger: "blur" }
  ]
};

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    word: "",
    type: SensitiveWordType.PROFANITY,
    severity: SeverityLevel.MEDIUM,
    filterMode: FilterMode.REPLACE,
    replacement: "",
    description: "",
    tags: [],
    status: 1
  });
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};

// 加载敏感词详情（编辑模式）
const loadWordDetail = async () => {
  if (!props.wordId) return;

  try {
    loading.value = true;
    const response = await getSensitiveWordDetailApi(props.wordId);

    if (response.code === 200 && response.data) {
      const data = response.data;
      Object.assign(form, {
        id: data.id,
        word: data.word,
        type: data.type,
        severity: data.severity,
        filterMode: data.filterMode,
        replacement: data.replacement || "",
        description: data.description || "",
        tags: SensitiveWordManagementUtils.parseTagList(data.tags),
        status: data.status
      });
    } else {
      ElMessage.error(response.message || "加载敏感词详情失败");
    }
  } catch (error) {
    console.error("加载敏感词详情失败:", error);
    ElMessage.error("加载敏感词详情失败");
  } finally {
    loading.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitting.value = true;

    const params = {
      ...form,
      tags: form.tags?.length ? form.tags : undefined
    };

    let response;
    if (props.mode === "create") {
      response = await createSensitiveWordApi(
        params as CreateSensitiveWordParams
      );
    } else {
      response = await updateSensitiveWordApi(
        params as UpdateSensitiveWordParams
      );
    }

    if (response.code === 200) {
      ElMessage.success(props.mode === "create" ? "创建成功" : "更新成功");
      emit("success");
    } else {
      ElMessage.error(
        response.message || (props.mode === "create" ? "创建失败" : "更新失败")
      );
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败");
  } finally {
    submitting.value = false;
  }
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

// 监听对话框可见性变化
watch(
  () => props.visible,
  visible => {
    if (visible) {
      if (props.mode === "edit" && props.wordId) {
        loadWordDetail();
      } else {
        resetForm();
      }
    }
  }
);
</script>

<style scoped>
/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .preview-card {
    background: #374151;
    border-color: #4b5563;
  }

  .preview-text {
    color: #e5e7eb;
  }

  .severity-desc,
  .mode-desc {
    color: #9ca3af;
  }

  .preview-label {
    color: #9ca3af;
  }
}

.severity-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.severity-desc {
  margin-left: 8px;
  font-size: 12px;
  color: #999;
}

.mode-desc {
  margin-left: 8px;
  font-size: 12px;
  color: #666;
}

.form-tip {
  margin-top: 4px;
}

.preview-card {
  background: #f8f9fa;
  border: 1px dashed #d9d9d9;
}

.preview-content {
  padding: 8px 0;
}

.preview-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.preview-item:last-child {
  margin-bottom: 0;
}

.preview-label {
  min-width: 80px;
  font-size: 14px;
  color: #666;
}

.preview-word {
  font-family: "Courier New", monospace;
  font-weight: 600;
}

.preview-text {
  font-size: 14px;
  color: #333;
}

.replaced-word {
  padding: 2px 4px;
  font-weight: 600;
  color: #67c23a;
  background: #f0f9ff;
  border-radius: 4px;
}

.blocked-text {
  padding: 2px 4px;
  font-weight: 600;
  color: #f56c6c;
  background: #fef0f0;
  border-radius: 4px;
}

.dialog-footer {
  text-align: center;
}
</style>
